﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AteneoLibri.Account
{
    public partial class GenerateNewPassword : System.Web.UI.Page
    {
        string recoveryCode = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                recoveryCode = HttpUtility.UrlEncode(Request.QueryString[0]);
            }
            catch (Exception)
            {
                if (recoveryCode.Equals(""))
                    recoveryCode = "Dashboard.aspx";

                Response.Redirect(HttpUtility.UrlDecode(recoveryCode));
            }

        }

        protected void btnNewPassword_Click(object sender, EventArgs e)
        {
            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
            {
                if (!recoveryCode.Equals("")) // c'è il parametro nella querystring
                {
                    Guid userId = service.getUserByRecoveryCode(recoveryCode);
                    AteneoLibriBusinessLogic.Entities.User user = service.getUserById(userId);

                    string hashedPassword = Utility.Utility.hash(txtNewPassword.Text.Trim());
                    user.Password = hashedPassword;

                    if (service.updatePassword(user))
                    {
                        pnlNewPassword.Visible = false;
                        pnlSentConfirmEmail.Visible = true;
                        // TODO: spedizione email conferma cambio password
                        Utility.Mail.MailSender mailSender = new Utility.Mail.MailSender();
                        mailSender.SendMail(user.Email, "Conferma cambio password", Utility.Mail.MailText.generateChangedPasswordBody(user.Email, txtNewPassword.Text.Trim()), true);
                    }
                    else
                    {
                        // TODO: creare pannello di errore aggiornamento psw
                    }
                }
            }
        }

        protected void btnAnnulla_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Dashboard.aspx");
        }
    }
}